import { useMutation, useQueryClient } from "@tanstack/react-query";
import { loginAPI } from "@/api";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import { useRefreshCaptcha } from "./use-captcha";
import { useNavigate, useSearchParams } from "react-router-dom";
import type { ErrorResponse, LoginResponseData, Response } from "@/types/response";
import type { LoginFormData } from "@/schemas/login";
import type { AxiosError } from "axios";

type LoginResponse = Response & { data: LoginResponseData };

/**
 * Login hooks
 */
export const useLogin = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const { mutate: refreshCaptcha } = useRefreshCaptcha();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const queryClient = useQueryClient();

  // 获取并解码service参数
  const getServiceParam = (): string | undefined => {
    const serviceParam = searchParams.get("service");
    if (serviceParam) {
      try {
        // URL解码service参数
        return decodeURIComponent(serviceParam);
      } catch (error) {
        console.error("Failed to decode service parameter:", error);
        return serviceParam;
      }
    }
    return undefined;
  };

  // 登录函数
  const login = (data: LoginFormData) => {
    // 获取service参数
    const service = getServiceParam();

    // 构建登录数据，包含service参数
    const loginData = {
      ...data,
      service: service || "",
    };

    loginMutation.mutate(loginData);
  };

  // Login mutation
  const loginMutation = useMutation({
    mutationFn: loginAPI.login,
    onSuccess: async (response: LoginResponse) => {
      if (response.code === 200) {
        // 使缓存失效，确保后续查询获取最新数据
        queryClient.invalidateQueries({ queryKey: ["user"] });

        // 登录成功，显示成功弹窗
        toast.success(t("Login successful"), {
          description:
            response.message ||
            t("You have successfully logged in.", {
              defaultValue: "You have successfully logged in.",
            }),
          duration: 5000,
        });

        const ticket = response.data.ticket;

        // 获取service参数，用于登录成功后跳转
        const service = getServiceParam();

        // 登录成功后跳转逻辑
        if (service) {
          // 如果有service参数，跳转到service页面，并添加st参数
          const url = new URL(service);
          url.searchParams.set("ticket", ticket);
          window.location.href = url.toString();
        } else {
          // 没有service参数，跳转到首页
          navigate("/cas");
        }
      } else {
        // 登录失败，显示错误弹窗并刷新验证码
        toast.error(t("Login failed"), {
          description:
            response.message ||
            t("An error occurred during login. Please try again."),
          duration: 5000,
        });
      }
      // 刷新验证码
      refreshCaptcha();
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      // 使用错误处理器获取错误信息
      const errorResult = errorHandler.handleApiError(error);

      // 根据错误类型显示不同颜色的弹窗
      if (errorResult.type === "warning") {
        toast.warning(t("Login failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Login failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      // 刷新验证码
      refreshCaptcha();
      console.error("Login error:", error);
    },
  });

  return {
    login,
    loginAsync: loginMutation.mutateAsync,
    isLogging: loginMutation.isPending,
    loginError: loginMutation.error,
  };
};
